package esb.chapter4.messageflow.servicemix;

import javax.annotation.Resource;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;
import javax.xml.transform.TransformerException;

import org.apache.log4j.Logger;
import org.apache.servicemix.MessageExchangeListener;
import org.apache.servicemix.components.util.ComponentSupport;
import org.apache.servicemix.jbi.jaxp.SourceTransformer;

public class MessageLogger extends ComponentSupport implements MessageExchangeListener {

	private final static Logger logger = Logger.getLogger(MessageLogger.class);
	private SourceTransformer sourceTransformer = new SourceTransformer();
	@Resource
	private DeliveryChannel channel;

    public void onMessageExchange(MessageExchange exchange) throws MessagingException {
    	NormalizedMessage inMessage = getInMessage(exchange);
        try {        	
        	logger.info("received payload " + sourceTransformer.toString(inMessage.getContent()));
        } catch(TransformerException e) {
        	logger.error("error while reading payload", e);
        }
        exchange.setStatus(ExchangeStatus.DONE);
        channel.send(exchange);
    }
}
